/**
 * Desenvolvido pela Fábrica de Software do CESUPA.
 * Todos os direitos reservados.
 */
package br.cesupa.fabsoft.nomedoprojeto.system.infra.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Filter used to check if the session contains a authenticated user. Checks the
 * current session for the "userLogged" boolean variable.
 *
 * @author Breno Leite
 */
public class AuthenticationFilter implements Filter {

    private HttpServletResponse httpServletResponse;
    private HttpSession httpSession;

    public void init(final FilterConfig config) throws ServletException {
    }

    public void doFilter(final ServletRequest servletRequest,
            final ServletResponse servletResponse, final FilterChain filterChain)
            throws IOException, ServletException {

        httpSession = ((HttpServletRequest) servletRequest).getSession();
        httpServletResponse = ((HttpServletResponse) servletResponse);

        if (isUserLogged()) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    }

    /**
     * Checks if the HTTP session contains a valid attribute indicating the
     * current user.
     *
     * @return true if there is some authenticated user, false otherwise
     */
    private boolean isUserLogged() {
        boolean returnvalue = true;
        Boolean isUserLogged = (Boolean) httpSession.getAttribute("userLogged");
        if (isUserLogged == null || isUserLogged.booleanValue() == false) {
            returnvalue = false;
        }

        return returnvalue;
    }

    public void destroy() {
    }
}
